package com.yungam.imcs.controller.message;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yungam.common.bean.message.Message;
import com.yungam.common.response.RetDTO;
import com.yungam.common.service.MessageService;
import com.yungam.common.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Api(tags = "消息管理页面接口")
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private MessageService messageService;
    @Resource
    private UserService userService;

    @ApiOperation("获取消息数据")
    @GetMapping("/list")
    public RetDTO<?> getMessageList(@ApiParam("开始时间") String start,
                                    @ApiParam("结束时间") String end,
                                    @ApiParam("接收人 id") Integer acceptManId) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("state").orderByDesc("send_time").eq("accept_man_id", acceptManId);
        if (StringUtils.isNotEmpty(start) && StringUtils.isNotEmpty(end)) {
            queryWrapper.between("send_time", start, end);
        }

        List<Message> list = messageService.list(queryWrapper);
        // 整合发送人信息
        for (Message message : list) {
            if (message.getSendManId() != null) message.setSendMan(userService.getById(message.getSendManId()));
        }
        return RetDTO.data(list);
    }

    @ApiOperation("获取所有未读消息")
    @GetMapping("/today")
    public RetDTO<?> getTodayMessageList(@ApiParam("接收人 id") Integer acceptManId) {
        if (acceptManId < 0) return RetDTO.data(null);
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", 0).orderByDesc("send_time").eq("accept_man_id", acceptManId);

        List<Message> list = messageService.list(queryWrapper);
        // 整合发送人信息
        for (Message message : list) {
            if (message.getSendManId() != null) message.setSendMan(userService.getById(message.getSendManId()));
        }
        return RetDTO.data(list);
    }

    @ApiOperation("已读消息")
    @PostMapping("check")
    public RetDTO<?> checkMessage(@ApiParam("消息 id 集合") @RequestBody List<Integer> checkedIds) {
        if (checkedIds.size() == 0) return RetDTO.success();

        for (Integer checkedId : checkedIds) {
            Message message = new Message();
            message.setId(checkedId);
            message.setState(1);
            message.setCheckTime(new Date());
            messageService.updateById(message);
        }
        return RetDTO.success();
    }

}
